<?php declare(strict_types=1);

namespace App\Middleware;

use App\Constants\Common\ApiStatusEnum;
use Hyperf\Context\Context;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Hyperf\HttpServer\CoreMiddleware;
use Hyperf\HttpMessage\Stream\SwooleStream;

/**
 * 重写路由找不到&请求方法不合法
 */
class RouteMethodNotFoundMiddleware extends CoreMiddleware
{
        /**
         * Handle the response when cannot found any routes.
         * @param ServerRequestInterface $request
         * @return ResponseInterface
         */
        protected function handleNotFound(ServerRequestInterface $request): ResponseInterface
        {
                // 重写路由找不到的处理逻辑
                $arrReturn = businessError(ApiStatusEnum::NOT_FOUND->getMessage(), ApiStatusEnum::NOT_FOUND->value);
                $jsonReturn = json_encode($arrReturn, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
                $response = Context::get(ResponseInterface::class);
                return $response->withHeader('Content-Type', $request->getHeader('content-type')[0] ?? 'application/json;charset=utf-8')
                        ->withHeader('Access-Control-Allow-Origin', $request->getHeader('origin')[0] ?? '*')
                        ->withHeader('Access-Control-Allow-Headers', ACCESS_CONTROL_ALLOW_HEADERS)
                        ->withHeader('Access-Control-Allow-Methods', ACCESS_CONTROL_ALLOW_METHODS)
                        ->withStatus(ApiStatusEnum::NOT_FOUND->value)->withBody(new SwooleStream($jsonReturn));

        }

        /**
         * Handle the response when the routes found but doesn't match any available methods.
         * @param array $methods
         * @param ServerRequestInterface $request
         * @return ResponseInterface
         */
        protected function handleMethodNotAllowed(array $methods, ServerRequestInterface $request): ResponseInterface
        {
                // 重写 HTTP 方法不允许的处理逻辑
                $arrReturn = businessError(ApiStatusEnum::METHOD_NOT_ALLOWED->getMessage(), ApiStatusEnum::METHOD_NOT_ALLOWED->value);
                $jsonReturn = json_encode($arrReturn, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
                $response = Context::get(ResponseInterface::class);
                return $response->withHeader('Content-Type', 'text/html;charset=utf-8')
                        ->withHeader('Access-Control-Allow-Origin', '*')
                        ->withHeader('Access-Control-Allow-Headers', ACCESS_CONTROL_ALLOW_HEADERS)
                        ->withHeader('Access-Control-Allow-Methods', ACCESS_CONTROL_ALLOW_METHODS)
                        ->withStatus(ApiStatusEnum::METHOD_NOT_ALLOWED->value)->withBody(new SwooleStream($jsonReturn));
        }
}